const _ = require('lodash/lang')

console.log('External file is also loaded!')
function _showPop(title, msg = '') {
  chrome.notifications.create({
    type: 'basic',
    title: title,
    message: msg,
    iconUrl: '../icons/38.png',
  })
}
async function _getLocalStorage(key) {
  return await chrome.storage.local.get([key])
}

async function _setLocalStorage(key, value) {
  let item = {}
  item[key] = value
  return await chrome.storage.local.set(item)
}
// 获取本地收藏夹
async function _getLocalBookmark() {
  return await chrome.bookmarks.getTree()
}

// 删除一个节点 包含子节点
async function _removeTree(id) {
  return await chrome.bookmarks.removeTree(id)
}

// 新增一个节点
async function _createBookmark(node) {
  return await chrome.bookmarks.create(node)
}

function _isDiff(remote, local) {
  let remoteUrls = _pickerUrl(remote)
  let localUrls = _pickerUrl(local)

  console.log('call _isDiff:', remoteUrls, localUrls)
  return _.isEqual(remoteUrls, localUrls)
}

// 提取 url
function _pickerUrl(bookmark, out = '') {
  if (out === '') out = {}
  for (let e of bookmark) {
    if (Object.hasOwnProperty.call(e, 'url') && e.url != null && e.url != '') out[e.url] = e.title
    if (Object.hasOwnProperty.call(e, 'children') && e.children.length > 0) _pickerUrl(e.children, out)
  }
  return out
}

// 级联数据扁平化
function _objToFlat(bookmark, out = '') {
  if (out == '') out = {}
  bookmark.forEach((e) => {
    if (Object.hasOwnProperty.call(e, 'url') && e.url != null && e.url != '') out[e.url] = e
    if (Object.hasOwnProperty.call(e, 'children') && e.children.length > 0) _objToFlat(e.children, out)
  })
  return out
}

// 新增标签页
function _createTabByurl(url) {
  chrome.tabs.create({ url })
}

async function _getBaseUrl() {
  let res = await _getLocalStorage('baseUrl')
  return JSON.stringify(res) == '{}' ? '' : res.baseUrl
}

async function _setBaseUrl(baseUrl) {
  return await _setLocalStorage('baseUrl', baseUrl)
}

// api请求封装
async function _fetch(opt) {
  let baseUrl = await _getBaseUrl()
  if (baseUrl == '') {
    baseUrl = 'http://36.111.45.214:5001/api/BookMarkManage/'
    await _setBaseUrl(baseUrl)
  }
  let url = ''
  let params = {}
  if (typeof opt == 'string') {
    url = opt
  } else {
    url = opt.url
    params['headers'] = Object.hasOwnProperty.call(opt, 'headers') ? opt.headers : { 'Content-Type': 'application/json;' }
    if (Object.hasOwnProperty.call(opt, 'method')) params['method'] = opt.method
    if (Object.hasOwnProperty.call(opt, 'body')) params['body'] = JSON.stringify(opt.body)
  }
  url
  const response = await fetch(baseUrl + url, params)
  return await response.json()
}

module.exports = {
  _showPop,
  _getLocalStorage,
  _setLocalStorage,
  _objToFlat,
  _getLocalBookmark,
  _removeTree,
  _createBookmark,
  _createTabByurl,
  _fetch,
  _getBaseUrl,
  _setBaseUrl,
  _isDiff,
}
